package com.time.company.components.profile;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ScreenUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.helper.picasso.PicassoImageLoader;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.ProfileParameters;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

/**
 * Created by Bing on 2017/12/5.
 * E-mail is tx16bing@163.com
 */

public class CommunicateActivity extends BaseActivity {

    private ImageView ivBg;
    private LinearLayout llBottom;
    private TextView tvTelephone;

    public static void start(Activity mContext) {
        Intent intent = new Intent(mContext, CommunicateActivity.class);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_communicate, "成为合作伙伴");
        assignViews();
        request();
    }

    private void assignViews() {
        ivBg = findView(R.id.iv_communicate_main);
        llBottom = findView(R.id.ll_bottom);
        tvTelephone = findView(R.id.tv_communicate_telephone);
        llBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                andPermission();
            }
        });
    }

    private void request() {
        if (NetWorkUtils.isNetAvailable(this)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress());
            ProfileParameters parameters = new ProfileParameters();
            parameters.setCommand(getString(R.string.command_becomePartners));
            parameters.setUserId(application.getAccount());
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, 90,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    private void andPermission() {
        // 需要调用AndPermission来开启定位权限提示
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.CALL_PHONE)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(CommunicateActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {
                // 表示打电话的权限申请通过
                //联系我们
                Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tvTelephone.getText().toString().trim()));
                callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(callIntent);
            }

        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 100) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort("请开启你的定位权限");
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(CommunicateActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(CommunicateActivity.this, 404).show();

            }

        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        switch (requestCode) {

            case 404:
                ToastUtils.showShort("开启定位权限回来");
                break;

            default:
                break;

        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;
        if (basicBean.isSuccess()){
            Partner partner = basicBean.parseData(Partner.class);
            if (null != partner){
                int height = ScreenUtils.getDisplayHeight() - ScreenUtils.getStatusBarHeight(this) -ScreenUtils.dip2px(93);
                PicassoImageLoader.loadImageViewSize(
                        CommunicateActivity.this,
                        partner.getBecomePartnersPic(),
                        ScreenUtils.getDisplayWidth(),
                        height,
                        R.drawable.iv_default_340_178,
                        R.drawable.iv_default_340_178,
                        toString(),
                        ivBg);
                tvTelephone.setText(partner.getCustomerServiceTelephoneNumbers());
            }
        }
    }

    class Partner{

        /**
         * customerServiceTelephoneNumbers : 客服电话
         * becomePartnersPic : 成为合作伙伴
         */

        @SerializedName("customerServiceTelephoneNumbers")
        private String customerServiceTelephoneNumbers;
        @SerializedName("becomePartnersPic")
        private String becomePartnersPic;

        public String getCustomerServiceTelephoneNumbers() {
            return customerServiceTelephoneNumbers;
        }

        public void setCustomerServiceTelephoneNumbers(String customerServiceTelephoneNumbers) {
            this.customerServiceTelephoneNumbers = customerServiceTelephoneNumbers;
        }

        public String getBecomePartnersPic() {
            return becomePartnersPic;
        }

        public void setBecomePartnersPic(String becomePartnersPic) {
            this.becomePartnersPic = becomePartnersPic;
        }
    }
}
